import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Observable } from 'rxjs';
import { AdminService } from 'src/modules/admin/admin/admin.service';
import { MerchantService } from 'src/modules/admin/merchant/merchant.service';
import { XjwtService } from 'src/xjwt/xjwt.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private configService:ConfigService, private xjwtService:XjwtService, private adminService:AdminService, private merchantService:MerchantService){}
  async canActivate(
    context: ExecutionContext,
  ): Promise<boolean>{

    let request = context.switchToHttp().getRequest();
    const white = this.configService.get<any[]>('white')
    const route = request.route
    let path:string = route.path
    const routePrefix = this.configService.get('routePrefix')
    if(routePrefix) {
      path = path.substr(routePrefix.length + 2) //path a/b
    }

    const token = request.headers.authorization
    const isRequiredLogin = white.includes(path) == false //是否要求登录

    if(isRequiredLogin && !token) { //需要登录
      return false
    }

    const loginJwt = this.configService.get('jwt.login')


    if(token) {
      let payload = this.xjwtService.verify(token, {secret : loginJwt.secret})
      if(isRequiredLogin && payload === null) {
        return false        
      }

      if(payload) {
        const roleType = payload.uid - payload.id - loginJwt.scale //角色类型
        const userId = (payload.key - loginJwt.scale) / loginJwt.scale
        request.userId = userId
        request.roleType = roleType
        if(roleType == 0) { //平台
          if(isRequiredLogin && !(await this.adminService.checkeAuth(userId, path))) return false


          request.isPlatform = true
          request.adminId = userId
        }else{
          if(isRequiredLogin && !(await this.merchantService.checkeAuth(userId, path))) return false

          request.merchantId = userId
          if(roleType == 1) { //一级商户
            request.isMerchant = true
          }else if(roleType == 2) { //二级商户
            request.isSubMerchant = true
          }
        }

      }

    }


    return true;
  }
}
